
<template>
  <div>
    <a-tabs default-active-key="1" @change="callback">

      <a-tab-pane key="1" tab=" 发布-招领/寻物">

        <a-form :form="form" @submit="handleSubmit">

          <a-form-item v-bind="formItemLayout">
      <span slot="label">
        标题&nbsp;
        <a-tooltip title="请确保标题有效性！">
          <a-icon type="question-circle-o" />
        </a-tooltip>
      </span>
            <a-input
                v-decorator="[
          'title',
          {
            rules: [{ required: true, message: '请一定要输入标题!', whitespace: true }],
          },
        ]"
            />
          </a-form-item>

          <a-form-item v-bind="formItemLayout" label="类别">

            <a-select
                ref="select"
                v-model:value="typeValue"
                style="width: 120px"
            >
              <a-select-option value="招领">招领</a-select-option>
              <a-select-option value="寻物">寻物</a-select-option>
            </a-select>

          </a-form-item>

          <a-form-item v-bind="formItemLayout" label="标签">

            <a-select mode="tags" style="width: 100%" placeholder="Tags Mode" @change="tagsHandleChange">
              <a-select-option v-for="i in LabelS" :key="i.labelId+''">
                {{i.name}}
              </a-select-option>
            </a-select>

          </a-form-item>

          <a-form-item v-bind="formItemLayout" label="内容">
            <a-auto-complete
                v-decorator="['text', { rules: [{ required: true, message: '您必须输入内容!' }] }]"
                placeholder="内容"
                @change="handleWebsiteChange"
            >

              <a-input />
            </a-auto-complete>
          </a-form-item>

          <a-form-item v-show="indexImageS" v-bind="formItemLayout" label="首页图片">
            <a-upload
                name="file",
                :headers="headers()"
                list-type="picture-card"
                class="avatar-uploader"
                :show-upload-list="false"
                :action=fileUpPath
                :before-upload="beforeUpload"
                @change="handleChange"
            >
              <img v-if="imageUrl" :src="imageUrl" alt="avatar" />
              <div v-else>
                <a-icon :type="loading ? 'loading' : 'plus'" />
                <div class="ant-upload-text">
                  Upload
                </div>
              </div>
            </a-upload>

          </a-form-item>

          <a-form-item v-show="listImageShow" v-bind="formItemLayout" label="额外补充图片">

            <div class="clearfix">
              <a-upload
                  :action=fileUpPath
                  :headers="headers()"
                  list-type="picture-card"
                  :file-list="fileList"
                  @preview="handlePreview"
                  @change="handleChangeTo"
              >
                <div v-if="fileList.length < 8">
                  <a-icon type="plus" />
                  <div class="ant-upload-text">
                    Upload
                  </div>
                </div>
              </a-upload>
              <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
                <img alt="example" style="width: 100%" :src="previewImage" />
              </a-modal>
            </div>

          </a-form-item>

          <a-form-item v-bind="tailFormItemLayout">
            <a-button type="primary" v-show="loginState" html-type="submit">
              发布
            </a-button>



            <a href="#/sign-in"  v-show="!loginState"> 登录之后发布 </a>

          </a-form-item>
        </a-form>

      </a-tab-pane>

      <a-tab-pane key="2" tab="已发布-招领/寻物" force-render>

        <IssueOkVue></IssueOkVue>

      </a-tab-pane>

    </a-tabs>
  </div>
</template>

<script>

	// "Authors" table component.
	import CardAuthorTable from '../components/Cards/CardAuthorTable' ;

	// "Projects" table component.
	import CardProjectTable2 from '../components/Cards/CardProjectTable2' ;

  import IssueOkVue from './modules/IssueOkVue';
  import { message } from 'ant-design-vue';


  function getBase64(img, callback) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  }

	export default ({
		components: {
			CardAuthorTable,
			CardProjectTable2,
      IssueOkVue,
		},
		data() {
			return {
        loginState:false,
        title:'',
        typeValue:"招领",
        text:'',
        indexImagePath:'',
        fjImageList:[],
        LostId:-1,
        ImageType:1,
        fileUpPath: 'http://localhost:18082/file/fileUp',
        LabelS:[],
        SeLabelS:[],
        indexImageS:false,
        listImageShow:false,
        confirmDirty: false,
        autoCompleteResult: [],
        formItemLayout: {
          labelCol: {
            xs: { span: 24 },
            sm: { span: 8 },
          },
          wrapperCol: {
            xs: { span: 24 },
            sm: { span: 16 },
          },
        },
        tailFormItemLayout: {
          wrapperCol: {
            xs: {
              span: 24,
              offset: 0,
            },
            sm: {
              span: 16,
              offset: 8,
            },
          },
        },
        loading: false,
        imageUrl: '',
        previewVisible: false,
        previewImage: '',
        fileList: [

        ],
			}
		},
    beforeCreate() {
      this.form = this.$form.createForm(this, { name: 'register' });

      console.log("开始拉取数据");
      /**
       * 这里去拉取lableS 数据
       */
      this.$http({
        method: 'post',
        url: 'http://localhost:18082/label/getall',
        data: {},
        headers:{
          user:localStorage.getItem("user"),
        }
      }).then((e)=>{




        this.LabelS=e.data.data;
        console.log("查看当前事项",e);
      })


    },
    mounted() {
      if(localStorage.getItem("user")==null||localStorage.getItem("user")==""){
        this.loginState=false;

        console.log("当前没有登录");
      }else{
        this.loginState=true;

        console.log("当前已经登录");

      }
    },
    methods: {
      tagsHandleChange(e){
        let ClZ=[];
        this.LabelS.forEach(item=>{
          e.forEach(item2=>{
            if(item2==item.labelId){
              ClZ.push(item);
            }
          })
        })

        this.SeLabelS=ClZ;
        console.log("看到了请联系我",e)
      },
      handleSubmit(e) {
        message.info('查看数据返回！',3);
          e.preventDefault();
          this.form.validateFieldsAndScroll((err, values) => {
            if (!err) {
              console.log(this.fileList)

              this.$http({
                method: 'post',
                url: 'http://localhost:18082/loatandfound/add',
                data: {
                  /**
                   * 首页图片路径
                   */
                  IndexImgPath: this.indexImagePath,
                  /**
                   * 标题
                   */
                  title: values.title,
                  lostType:this.typeValue,
                  //内容
                  text:values.text,
                  //标签
                  labels:this.SeLabelS,
                  //状态
                  state:'未找到',
                  //附件图片集ID
                  imageIds:this.fjImageList
                },
                headers:{
                  user:localStorage.getItem("user"),
                }
              }).then((e)=>{

                  if(e.data.status==true){
                    message.info('发布成功！现在你可以补充首页图片和详情图片了🙂',3);
                    this.indexImageS=true;
                    this.listImageShow=true;
                    this.LostId=e.data.data.lostId;
                  }
              })

              console.log('Received values of form: ', values);

            }
          });
        },
      handleConfirmBlur(e) {
          const value = e.target.value;
          this.confirmDirty = this.confirmDirty || !!value;
        },
      compareToFirstPassword(rule, value, callback) {
          const form = this.form;
          if (value && value !== form.getFieldValue('password')) {
            callback('Two passwords that you enter is inconsistent!');
          } else {
            callback();
          }
        },
      validateToNextPassword(rule, value, callback) {
          const form = this.form;
          if (value && this.confirmDirty) {
            form.validateFields(['confirm'], { force: true });
          }
          callback();
        },
      handleWebsiteChange(value) {
          let autoCompleteResult;
          if (!value) {
            autoCompleteResult = [];
          } else {
            autoCompleteResult = ['.com', '.org', '.net'].map(domain => `${value}${domain}`);
          }
          this.autoCompleteResult = autoCompleteResult;
        },
      callback(key) {
        console.log(key);
      },
      handleChange(info) {
        if (info.file.status === 'uploading') {
          this.loading = true;
          return;
        }
        if (info.file.status === 'done') {
          // Get this url from response in real world.
          getBase64(info.file.originFileObj, imageUrl => {
            this.imageUrl = imageUrl;
            this.loading = false;
          });
        }
      },
      beforeUpload(file) {
        /**
         * 这标题当前上传的是 主页图片
         * @type {number}
         */
        this.ImageType=1;
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
          this.$message.error('You can only upload JPG file!');
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
          this.$message.error('Image must smaller than 2MB!');
        }
        return isJpgOrPng && isLt2M;
      },
      headers() {
        return {
          "LostId": this.LostId,
          "ImageType": this.ImageType,
        }
      },
      handleCancel() {
        this.previewVisible = false;
      },
      async handlePreview(file) {
        /**
         * 这标题当前上传的是 列表图片图片
         * @type {number}
         */
        this.ImageType=2;
        if (!file.url && !file.preview) {
          file.preview = await getBase64(file.originFileObj);
        }
        this.previewImage = file.url || file.preview;
        this.previewVisible = true;

      },
      handleChangeTo({ fileList }) {
        console.log(fileList);
        this.fileList = fileList;
      },
    },
	})

</script>

<style lang="scss">
</style>